import React from 'react';

import { Row, Col, Tabs, Button, Tooltip } from 'antd';
import { randomKey } from '../../../../utils/utils';
import WarningList from './WarningList';
import CommonListsIndex from 'src/components/CommonLists/index';
import FilterTool from 'src/components/FilterTool';
import moment from 'moment';
import LineStackChart from 'src/components/Chart/LineStackChart';
import services from 'src/services/api';

import { tooltipFormatter } from '../utils';

const { TabPane } = Tabs;
export default class WarningMonitorning extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = '';
    this.listsComponent = WarningList;

    this.queryParams = {};
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.state = {
      ...this.state,
      type: 'node',
      node: [],
      server: [],
      api: [],
      middleware: [],
      nodeDetail: [],
      serverDetail: [],
      apiDetail: [],
      middlewareDetail: [],
    };
  }
  componentDidMount() {}

  // 列表
  queryList(params) {
    const { current_page, page_size, ...statisticsParams } = params;
    this.getStatistics(statisticsParams);
    this.getDetail(params);
  }
  getStatistics = (params) => {
    const { type } = this.state;
    services.devOpt.warningMonitor({ type: type, ...params }).then((res) => {
      if (res.code === 0) {
        this.setState({
          [type]: res.data,
        });
      }
    });
  };
  getDetail = (params) => {
    const { type } = this.state;
    services.devOpt.warningMonitorDetail({ type: type, ...params }).then((res) => {
      if (res.code === 0) {
        // 大数据分页？？
        this.queryParams.total_count = res.data.totalCount;
        this.queryParams.next_id = res.data.nextId;
        this.queryParams.previous_id = res.data.previousId;
        this.queryParams.previous_page = res.data.previousPage;
        // 设置key值
        try {
          res.data.list.forEach((o, index) => {
            o.key = randomKey();
          });
        } catch {}

        this.setState({
          [`${type}Detail`]: res.data,
        });
      }
    });
  };
  render() {
    const { type, node, server, api, middleware, nodeDetail, middlewareDetail, serverDetail, apiDetail } = this.state;
    const filterItems = [
      {
        type: 'rangepicker',
        key: 'start',
        name: ['start', 'end'],
        label: '时间',
        defaultValue: [
          moment()
            // 展示进7天的数据，包括今天，所以是6
            .subtract(6, 'day')
            .startOf('day')
            .format('YYYY-MM-DD HH:mm'),
          moment().format('YYYY-MM-DD HH:mm'),
        ],
        disabledDate: (current) => {
          return (
            current &&
            (current > moment().endOf('day') ||
              current <
                moment()
                  .subtract(30, 'day')
                  .endOf('day'))
          );
          // return current && current > moment().endOf('day');
        },
        ranges: {
          本周: [moment().startOf('week'), moment()],
          近7天: [moment().subtract('days', 6), moment()],
          本月: [moment().startOf('month'), moment()],
          近30天: [moment().subtract('days', 29), moment()],
        },
        format: 'YYYY-MM-DD HH:mm',
        placeholder: ['起始时间', '结束时间'],
        allowClear: false,
      },
    ];
    return (
      <Tabs
        activeKey={type}
        onChange={(key) => this.setState({ type: key })}
        tabBarExtraContent={
          <Button type='link' onClick={() => this.props.history.push('/monitor/devOps/warning/setting')}>
            报警规则设置
          </Button>
        }
        destroyInactiveTabPane
      >
        <TabPane tab='应用节点' key='node'>
          <div className='detail-page'>
            <FilterTool
              data={filterItems}
              colNum={4}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              refresh={this.resetList}
              isOnChange={true}
              justify='start'
            />
            <Row style={{ marginTop: '20px' }}>
              <Col span={24} style={{ marginBottom: '20px' }}>
                <div className='risk-trend-box'>
                  <div className='chart-box'>
                    <LineStackChart
                      id='node'
                      width='100%'
                      height='300px'
                      dataSource={node}
                      xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                      dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                      tooltipFormatter={(params) => {
                        return tooltipFormatter(params, 2);
                      }}
                    />
                  </div>
                </div>
              </Col>
              <Col span={24}>
                <div className='inner-content'>
                  <WarningList
                    {...nodeDetail}
                    rowKey='key'
                    columns={[
                      { dataIndex: 'time', title: '报警时间', key: 'time' },
                      { dataIndex: 'app', title: '应用名称', key: 'app' },
                      { dataIndex: 'ip', title: '节点IP', key: 'ip' },
                      {
                        dataIndex: 'remark',
                        title: '触发详情',
                        key: 'remark',
                        render: (text) => (
                          <Tooltip title={text} placement='topLeft'>
                            {text}
                          </Tooltip>
                        ),
                      },
                    ]}
                    onChangePagination={this.onChangePagination}
                  />
                </div>
              </Col>
            </Row>
          </div>
        </TabPane>
        <TabPane tab='服务器性能' key='server'>
          <div className='detail-page'>
            <FilterTool
              data={filterItems}
              colNum={4}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              refresh={this.resetList}
              isOnChange={true}
              justify='start'
            />
            <Row style={{ marginTop: '20px' }}>
              <Col span={24} style={{ marginBottom: '20px' }}>
                <div className='risk-trend-box'>
                  <div className='chart-box'>
                    <LineStackChart
                      id='server'
                      width='100%'
                      height='300px'
                      dataSource={server}
                      xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                      dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                      tooltipFormatter={(params) => {
                        return tooltipFormatter(params, 2);
                      }}
                    />
                  </div>
                </div>
              </Col>
              <Col span={24}>
                <div className='inner-content'>
                  <WarningList
                    {...serverDetail}
                    rowKey='key'
                    columns={[
                      { dataIndex: 'time', title: '报警时间', key: 'time' },
                      { dataIndex: 'server', title: '机器名称', key: 'server' },
                      { dataIndex: 'ip', title: '节点IP', key: 'ip' },
                      {
                        dataIndex: 'remark',
                        title: '触发详情',
                        key: 'remark',
                        render: (text) => (
                          <Tooltip title={text} placement='topLeft'>
                            {text}
                          </Tooltip>
                        ),
                      },
                    ]}
                    onChangePagination={this.onChangePagination}
                  />
                </div>
              </Col>
            </Row>
          </div>
        </TabPane>
        <TabPane tab='接口调用' key='api'>
          <div className='detail-page'>
            <FilterTool
              data={filterItems}
              colNum={4}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              refresh={this.resetList}
              isOnChange={true}
              justify='start'
            />
            <Row style={{ marginTop: '20px' }}>
              <Col span={24} style={{ marginBottom: '20px' }}>
                <div className='risk-trend-box'>
                  <div className='chart-box'>
                    <LineStackChart
                      id='api'
                      width='100%'
                      height='300px'
                      dataSource={api}
                      xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                      dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                      tooltipFormatter={(params) => {
                        return tooltipFormatter(params, 2);
                      }}
                    />
                  </div>
                </div>
              </Col>
              <Col span={24}>
                <div className='inner-content'>
                  <WarningList
                    {...apiDetail}
                    rowKey='key'
                    columns={[
                      { dataIndex: 'time', title: '报警时间', key: 'time' },
                      { dataIndex: 'source', title: '异常来源', key: 'source' },
                      {
                        dataIndex: 'remark',
                        title: '触发详情',
                        key: 'remark',
                        render: (text) => (
                          <Tooltip title={text} placement='topLeft'>
                            {text}
                          </Tooltip>
                        ),
                      },
                    ]}
                    onChangePagination={this.onChangePagination}
                  />
                </div>
              </Col>
            </Row>
          </div>
        </TabPane>
        <TabPane tab='中间件' key='middleware'>
          <div className='detail-page'>
            <FilterTool
              data={filterItems}
              colNum={4}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              refresh={this.resetList}
              isOnChange={true}
              justify='start'
            />
            <Row style={{ marginTop: '20px' }}>
              <Col span={24} style={{ marginBottom: '20px' }}>
                <div className='risk-trend-box'>
                  <div className='chart-box'>
                    <LineStackChart
                      id='middleware'
                      width='100%'
                      height='300px'
                      dataSource={middleware}
                      xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                      dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                      tooltipFormatter={(params) => {
                        return tooltipFormatter(params, 2);
                      }}
                    />
                  </div>
                </div>
              </Col>
              <Col span={24}>
                <div className='inner-content'>
                  <WarningList
                    {...middlewareDetail}
                    rowKey='key'
                    columns={[
                      { dataIndex: 'time', title: '报警时间', key: 'time' },
                      { dataIndex: 'source', title: '异常来源', key: 'source' },
                      {
                        dataIndex: 'remark',
                        title: '触发详情',
                        key: 'remark',
                        render: (text) => (
                          <Tooltip title={text} placement='topLeft'>
                            {text}
                          </Tooltip>
                        ),
                      },
                    ]}
                    onChangePagination={this.onChangePagination}
                  />
                </div>
              </Col>
            </Row>
          </div>
        </TabPane>
      </Tabs>
    );
  }
}
